﻿using ContosoUniversity.Models;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ContosoUniversity.Tools
{
    public class PaginatedList<T> : List<T>
    {
        /// <summary>
        /// 当前页
        /// </summary>
        public int PageIndex { get; private set; }
        /// <summary>
        /// 总页数
        /// </summary>
        public int TotalPages { get; private set; }
        /// <summary>
        /// 是否是第一页
        /// </summary>
        public bool HasPreviousPage
        {
            get { return PageIndex > 1; }
        }
        /// <summary>
        /// 是否最后一页
        /// </summary>
        public bool HasNextPage
        {
            get { return PageIndex < TotalPages; }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="items">数据源</param>
        /// <param name="count">数据条数</param>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">页容量</param>
        public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
        {
            PageIndex = pageIndex;
            //有小数都加1
            TotalPages = (int)Math.Ceiling(count / (double)pageSize);
            this.AddRange(items);
        }



        public static async Task<PaginatedList<T>> CreateAsync(IQueryable<T> source, int pageIndex, int pageSize)
        {
            var count = await source.CountAsync();
            var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
            return new PaginatedList<T>(items, count, pageIndex, pageSize);
        }

        internal Task<string> CreateAsync(IQueryable<Student> queryable)
        {
            throw new NotImplementedException();
        }
    }
}
